package rattlesnake.callback.config.interceptor;

import org.apache.commons.lang.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import rattlesnake.callback.config.constant.CallBackConstant;
import rattlesnake.callback.core.cache.Cache;
import rattlesnake.callback.core.cache.CacheManager;
import rattlesnake.callback.core.cache.Element;
import rattlesnake.callback.util.ObjectUtil;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Package: rattlesnake.callback.config.interceptor
 * @Description: 1:记录执行时间 2:对信息进行去重
 * @author: liuxin
 * @date: 17/4/10 下午1:52
 */
public class UniqueInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(UniqueInterceptor.class);

    CacheManager cacheManager;

    public void setCacheManager(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    /**
     *
     * @param request
     * @param response
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        logger.info("============================拦截器启动==============================");
        request.setAttribute("starttime", System.currentTimeMillis());
        String cacheName = (String) request.getAttribute(CallBackConstant.CACHENAME);
        String messageCode = (String) request.getAttribute(CallBackConstant.MESSAGECODE);
        cacheManager.getCache(cacheName);
        String[] cacheNames = cacheManager.getCacheNames();
        for (String name : cacheNames) {
            logger.debug("缓存名称:{}", name);
        }
        logger.debug("当前存放CacheName:{}",cacheName);
        Cache cache = cacheManager.getCache(cacheName);
        if (ObjectUtil.isEmpty(cache)){//初始化时候就会存在，如果没有存在就是没有经过过滤器处理的，则直接放行
            return true;
        }
        Element element = cache.get(messageCode);
        if (ObjectUtil.isEmpty(element)) {
            cache.put(new Element(messageCode, true));
            //通过
            return true;
        }
        logger.debug("=========================重复推送=========================");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("===========================执行处理完毕=============================");
        long starttime = (long) request.getAttribute("starttime");
        request.removeAttribute("starttime");
        long endtime = System.currentTimeMillis();
        logger.info("============请求地址：" + request.getRequestURI() + "：处理时间：{}", (endtime - starttime) + "ms");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("============================拦截器关闭==============================");
    }
}
